<template>
    <div class="layOut">
        <div class="configure-title">
            <span class="header_text">最近修改时间为：{{ last_update ? last_update : '--' }}</span>
            <el-button type="primary" @click="addEnterprise">新增企业属性</el-button>
        </div>
        <el-table
            v-if="showTable"
            id="tableRef"
            :row-class-name="tableRowClassName"
            header-row-class-name="table_header_title"
            class="configure-table-box5"
            :data="tabList">
            <el-table-column width="55">
                <template #default="scope">
                    <img
                        v-if="scope.$index != 0 && scope.$index != tabList.length"
                        src="@/assets/customer/sort-icon.png"
                        class="sortImg"
                        alt="" />
                </template>
            </el-table-column>
            <el-table-column label="属性名" prop="name" />
            <el-table-column prop="typeName" label="格式">
                <template #default="scope">
                    {{ scope.row.typeName || '--' }}
                </template>
            </el-table-column>
            <el-table-column label="选项内容">
                <template #default="scope">
                    <el-popover
                        v-if="scope.row.attr_val_name?.length > 15"
                        placement="top-start"
                        :width="200"
                        trigger="hover">
                        <template #reference>
                            <p class="content_select">{{ scope.row.attr_val_name || '--' }}</p>
                        </template>
                        <template #default>
                            <p>{{ scope.row.attr_val_name || '--' }}</p>
                        </template>
                    </el-popover>
                    <p v-else class="content_select">{{ scope.row.attr_val_name || '--' }}</p>
                </template>
            </el-table-column>
            <el-table-column label="限制">
                <template #default="{ row }"> {{ row.max_length ? row.max_length : '--' }} </template>
            </el-table-column>
            <el-table-column label="状态">
                <template #default="{ row }">
                    {{ row.is_enable ? (row.is_enable == 1 ? '已开启' : '未开启') : '--' }}
                </template>
            </el-table-column>
            <el-table-column label="类型">
                <template #default="{ row }">
                    <span>{{ row.is_system ? (row.is_system == 1 ? '系统' : '自定义') : '--' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="必填">
                <template #default="{ row }">
                    <span>{{ row.is_required ? (row.is_required == 1 ? '否' : '是') : '--' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="创建人">
                <template #default="{ row }">
                    <span>{{ row.created_name ? row.created_name : '--' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" width="180">
                <template #default="{ row }">
                    <span>{{ row.created_at ? row.created_at : '--' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="290">
                <template #default="scope">
                    <div :data-id="scope.$index">
                        <el-button size="small" :disabled="scope.row.can_operate == 2" @click="start(scope.row)">{{
                            scope.row.is_enable == 1 ? '关闭' : '开启'
                        }}</el-button>
                        <el-button v-if="scope.row.is_system == 2" size="small" @click="edit(scope.row)"
                            >编辑</el-button
                        >
                        <el-button v-if="scope.row.is_system == 2" size="small" @click="del(scope.row)">删除</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <Dialog :app-dialog="appDialog">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
            <el-form-item label="属性名称" prop="attr_name">
                <el-input v-model="ruleForm.attr_name" maxlength="15" show-word-limit placeholder="请输入属性名称" />
            </el-form-item>
            <el-form-item label="属性格式" prop="attr_type">
                <el-select v-model="ruleForm.attr_type" placeholder="请选择属性格式">
                    <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item
                v-if="ruleForm.attr_type == 'textbox' || ruleForm.attr_type == 'textarea'"
                label="文本限制"
                prop="max_length">
                <el-input v-model.number="ruleForm.max_length" placeholder="请输入文本限制"></el-input>
            </el-form-item>
            <el-form-item
                v-if="ruleForm.attr_type == 'select' || ruleForm.attr_type == 'muti_select'"
                label="选项内容"
                prop="content">
                <el-input
                    v-model="ruleForm.content"
                    type="textarea"
                    placeholder="每个选项为一行，最多30个选项"
                    @blur="checkTextarea"></el-input>
            </el-form-item>
            <el-form-item label="是否开启" prop="is_enable">
                <el-radio-group v-model="ruleForm.is_enable">
                    <el-radio :label="1">开启</el-radio>
                    <el-radio :label="2">关闭</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="是否必填" prop="is_required">
                <el-select v-model="ruleForm.is_required" placeholder="请选择是否必填">
                    <el-option label="是" :value="2" />
                    <el-option label="否" :value="1" />
                </el-select>
            </el-form-item>
        </el-form>
    </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, onMounted } from 'vue';
import Sortable from 'sortablejs';
import { Plus } from '@element-plus/icons-vue';
import { getEnterprise, sortEnterprise, addNewEnterprise, editEnterprise, delEnterprise, startOrDel } from '../api';
import Dialog from '@/components/Dialog.vue';
import { deepCopy } from '@/utils/helper';
import { ElMessage, ElMessageBox } from 'element-plus';
import { tableH, reSize } from '@/utils/utils';
const tabList = ref([]);
const ruleFormRef = ref(null);
const showTable = ref(true);
const last_update = ref('');
const editId = ref();
const typeList = reactive([
    { label: '单行文本', value: 'textbox' },
    { label: '多行文本', value: 'textarea' },
    { label: '单选', value: 'select' },
    { label: '多选', value: 'muti_select' },
    { label: '日期', value: 'date' },
    { label: '手机号', value: 'mobile' },
    { label: '邮箱', value: 'email' },
    { label: '区域', value: 'pca' },
    { label: '图片', value: 'picture' }
]);
const ruleForm = reactive({
    attr_name: '',
    attr_type: '',
    attr_val: [],
    max_length: '',
    is_enable: '',
    is_required: '',
    content: ''
});
const rules = reactive({
    attr_name: [{ required: true, message: '请输入属性名称', trigger: 'blur' }],
    attr_type: [{ required: true, message: '请选择属性格式', trigger: 'blur' }],
    content: [{ required: true, message: '请填写选项内容', trigger: 'blur' }],
    is_enable: [{ required: true, message: '请选择是否开启', trigger: 'blur' }],
    max_length: [{ required: true, message: '请输入文本限制', trigger: 'blur' }],
    is_required: [{ required: true, message: '请选择是否必填', trigger: 'blur' }]
});
const setSortableFun = () => {
    let nowIndex;
    let copyTableList;
    nextTick(() => {
        const SortableBox = new Sortable(
            document.querySelector('#tableRef').querySelector('.el-table__body-wrapper tbody'),
            {
                animation: 100,
                sort: true,
                delay: 0,
                delayOnTouchOnly: false,
                handle: '.can-sort',
                filter: '.no-sort',
                onChoose: function (evt: any) {
                    nowIndex = evt.oldIndex;
                },
                onMove: function (evt: any, originalEvent: any) {},
                //
                onEnd: (evt: any) => {
                    copyTableList = JSON.parse(JSON.stringify(tabList.value));
                    const data = copyTableList.splice(evt.oldIndex, 1)[0];
                    copyTableList.splice(evt.newIndex, 0, data);
                    let next_id, pre_id;
                    if (copyTableList[evt.newIndex - 1]) {
                        pre_id = copyTableList[evt.newIndex - 1].source_id;
                    }
                    if (copyTableList[evt.newIndex + 1]) {
                        next_id = copyTableList[evt.newIndex + 1].source_id;
                    }
                    const arr: any = [];
                    copyTableList.forEach((item: any, index: number) => {
                        arr.push(item.id);
                    });
                    sortEnterprise({ attr_ids: arr }).then((r: any) => {
                        init();
                    });
                }
            }
        );
    });
};
const init = () => {
    getEnterprise().then((res: any) => {
        showTable.value = false;
        last_update.value = res.lately_update_time;
        tabList.value = res.data.map((item: any) => {
            if (item.type) {
                const index = typeList.findIndex(it => it.value == item.type);
                item.typeName = '';
                if (index > -1) {
                    item.typeName = typeList[index].label;
                }
            }
            item.attr_val_name = item.attr_val_name ? item.attr_val_name : '';
            return item;
        });
        setTimeout(() => {
            showTable.value = true;
            nextTick(() => {
                setSortableFun();
            });
        });
    });
};

const tableRowClassName = (row: any) => {
    if (row.rowIndex == 0 || row.rowIndex == tabList.value.length) {
        return 'no-sort';
    }
    return 'can-sort';
};
const addEnterprise = () => {
    appDialog.visible = true;
};
const edit = (data: any) => {
    const { name, type, content, is_enable, is_required, id, max_length, attr_val_name } = data;
    ruleForm.attr_name = name;
    ruleForm.attr_type = type;
    ruleForm.content = content;
    ruleForm.is_enable = is_enable;
    ruleForm.is_required = is_required;
    ruleForm.max_length = max_length;
    ruleForm.content = attr_val_name ? attr_val_name.toString().replace(/,/g, '\n') : '';
    ruleForm.attr_id = id;
    appDialog.visible = true;
};
const del = (row: any) => {
    ElMessageBox.confirm(
        `您正在删除企业的【${row.name}】的属性，确定之后，企业的该属性将会被删除，请慎重！`,
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        delEnterprise({ attr_id: row.id }).then((r: object) => {
            ElMessage.success('删除成功');
            init();
        });
    });
};
const start = (row: any) => {
    const params = {
        attr_id: row.id,
        is_enable: row.is_enable == 1 ? 2 : 1
    };
    startOrDel(params).then((res: any) => {
        ElMessage.success('操作成功');
        init();
    });
};
// 检查是否输入标准  防止ssr
const checkTextarea = () => {
    let str = ruleForm.content;
    str = str.replace(/<script>/g, '');
    str = str.replace(/alert/g, '');
    ruleForm.content = str;
};
const getContentArr = (str: string) => {
    if (!str.trim().length) {
        return [];
    }
    let arr: any = [];
    str.split('\n').forEach(item => {
        if (item.length > 0) {
            arr.push(item);
        }
    });
    arr = Array.from(new Set(arr)); //去除重复的
    return arr;
};
const cancelHandel = (refresh?: number) => {
    if (!ruleFormRef.value) return;
    Object.keys(ruleForm).reduce((val, key) => {
        if (ruleForm[key] == 'attr_val') {
            ruleForm[key] = [];
        } else {
            ruleForm[key] = '';
        }
    }, {});
    appDialog.visible = false;
    if (refresh == 1) init();
};
const submitHandel = async () => {
    if (!ruleFormRef.value) return;
    await ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
            ruleForm.attr_val = getContentArr(ruleForm.content);
            const params = deepCopy(ruleForm);
            delete params.content;
            if (params.attr_id) {
                editEnterprise(params).then((res: any) => {
                    ElMessage.success('编辑成功');
                    cancelHandel(1);
                });
            } else {
                addNewEnterprise(params).then((res: any) => {
                    ElMessage.success('新建成功');
                    cancelHandel(1);
                });
            }
        } else {
        }
    });
};
// 弹框配置项
const appDialog = reactive({
    visible: false,
    title: '新增企业属性',
    width: '30%',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '提交',
    isInit: false, //是否重置
    isChooseDisabled: false //重新打开传递进来的数据是否重置
});
nextTick(() => {
    init();
});
</script>

<style lang="scss" scoped>
.layOut {
    background-color: #fff;

    .configure-title {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .header_text {
            font-size: 14px;
            font-family: STHeitiSC-Light, STHeitiSC;
            color: #33302d;
        }
    }

    .configure-table-box5 {
        margin-top: 17px;

        // overflow: hidden;
        .sortImg {
            width: 13px;
            height: 11px;
        }
    }

    .pageLimit-box {
        padding-top: 20px;
    }
}

.el-select {
    width: 100%;
}

.content_select {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

:deep(.el-table--layout-fixed .el-table__header-wrapper tr th.el-table-fixed-column--right) {
    background-color: #f9f9f9;
}
</style>
